package com.dushibao.front;

import com.dushibao.common.Constants;
import com.dushibao.entity.User;
import com.dushibao.service.UserService;
import com.dushibao.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@WebServlet("/loginFinish")
public class LoginFinishServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        String rememberMe = req.getParameter("rememberMe");
        Cookie userNameCookie = new Cookie("userName",URLEncoder.encode(userName, "UTF-8"));
        Cookie passwordCookie = new Cookie("password",URLEncoder.encode(password,"UTF-8"));

        if("true".equalsIgnoreCase(rememberMe)){
            userNameCookie.setMaxAge(24*60*60);
            passwordCookie.setMaxAge(24*60*60);
        }else{
            userNameCookie.setMaxAge(0);
            passwordCookie.setMaxAge(0);
        }
        resp.addCookie(userNameCookie);
        resp.addCookie(passwordCookie);

        List<User> users = userService.queryByUserNameAndPassword(userName,password);

        if(users!=null && users.size() == 1){
            req.getSession().setAttribute("user",users.get(0));
            resp.getWriter().write(Constants.SUCCESS.toString());//1000代表是成功
        }else{
            resp.getWriter().write("1001");
        }

    }
}
